package com.maintain.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.ChartsRequestData;
import com.entity.ZichanjiechuEntity;
import com.entity.view.ZichanjiechuView;
import com.entity.RecordRequest;
import com.feign.TokenFeignService;
import com.feign.ZiChanFeignService;
import com.maintain.service.RedisService;
import com.maintain.service.ZichanjiechuService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 资产借出
 * 后端接口
 *
 * @author
 * @email
 * @date 2021-05-11 09:16:46
 */
@RestController
@RequestMapping("/zichanjiechu")
public class ZichanjiechuController {
    @Autowired
    private ZichanjiechuService zichanjiechuService;
    @Autowired
    private TokenFeignService tokenFeignService;
    @Autowired
    private ZiChanFeignService ziChanFeignService;

    @Resource
    private RedisService redisService;


    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, ZichanjiechuEntity zichanjiechu,
                  HttpServletRequest request) {
        String tableName = tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getTablename();
        if (tableName.equals("yonghu")) {
            zichanjiechu.setYonghuming(tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getUsername());
        }
        EntityWrapper<ZichanjiechuEntity> ew = new EntityWrapper<ZichanjiechuEntity>();
        PageUtils page = zichanjiechuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, zichanjiechu), params), params));

        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, ZichanjiechuEntity zichanjiechu,
                  HttpServletRequest request) {
        EntityWrapper<ZichanjiechuEntity> ew = new EntityWrapper<ZichanjiechuEntity>();
        PageUtils page = zichanjiechuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, zichanjiechu), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/lists")
    public R list(ZichanjiechuEntity zichanjiechu) {
        EntityWrapper<ZichanjiechuEntity> ew = new EntityWrapper<ZichanjiechuEntity>();
        ew.allEq(MPUtil.allEQMapPre(zichanjiechu, "zichanjiechu"));
        return R.ok().put("data", zichanjiechuService.selectListView(ew));
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(ZichanjiechuEntity zichanjiechu) {
        EntityWrapper<ZichanjiechuEntity> ew = new EntityWrapper<ZichanjiechuEntity>();
        ew.allEq(MPUtil.allEQMapPre(zichanjiechu, "zichanjiechu"));
        ZichanjiechuView zichanjiechuView = zichanjiechuService.selectView(ew);
        return R.ok("查询资产借出成功").put("data", zichanjiechuView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        ZichanjiechuEntity zichanjiechu = (ZichanjiechuEntity) redisService.get("Zichanjiechu" + id);
        if (zichanjiechu == null) {
            zichanjiechu = zichanjiechuService.selectById(id);
            redisService.set("Zichanjiechu" + id, zichanjiechu);
        }
        return R.ok().put("data", zichanjiechu);
    }

    /**
     * 前端详情
     */
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        ZichanjiechuEntity zichanjiechu = (ZichanjiechuEntity) redisService.get("Zichanjiechu" + id);
        if (zichanjiechu == null) {
            zichanjiechu = zichanjiechuService.selectById(id);
            redisService.set("Zichanjiechu" + id, zichanjiechu);
        }
        return R.ok().put("data", zichanjiechu);
    }


    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ZichanjiechuEntity zichanjiechu, HttpServletRequest request) {
        zichanjiechu.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(zichanjiechu);
        zichanjiechuService.insert(zichanjiechu);
        redisService.set("Zichanjiechu" + zichanjiechu.getId(), zichanjiechu);
        return R.ok();
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody ZichanjiechuEntity zichanjiechu, HttpServletRequest request) {
        zichanjiechu.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(zichanjiechu);
        zichanjiechuService.insert(zichanjiechu);
        redisService.set("Zichanjiechu" + zichanjiechu.getId(), zichanjiechu);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ZichanjiechuEntity zichanjiechu, HttpServletRequest request) {
        final Long id = zichanjiechu.getId();
        ZichanjiechuEntity zichanjiechuEntity = zichanjiechuService.selectById(id);
        String sfsh = zichanjiechu.getSfsh();
        final Integer shuliang = zichanjiechu.getShuliang();
        //ValidatorUtils.validateEntity(zichanjiechu);
        //不通过资产加回去
        if (zichanjiechuEntity.getSfsh().equals("是")) {
            return R.error("已审核通过");
        }
        if (sfsh.equals("否")) {
            ziChanFeignService.record(zichanjiechu.getZichanbianhao(), shuliang);
        }


        zichanjiechuService.updateById(zichanjiechu);//全部更新
        redisService.set("Zichanjiechu" + zichanjiechu.getId(), zichanjiechu);

        return R.ok();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        zichanjiechuService.deleteBatchIds(Arrays.asList(ids));
        for (Long id : ids) {
            redisService.delete("Zichanjiechu" + id);
        }
        return R.ok();
    }

    /**
     * 是否有借出记录
     * <p>
     * author : yue
     */
    @PostMapping("/record")
    public ZichanjiechuEntity record(@RequestBody RecordRequest request) {
        //检查归还的这个物品是否存在于借出表中且是当前用户
        // 在zichanjiechu表中查询是否存在符合条件的借出记录
        Wrapper<ZichanjiechuEntity> queryWrapper = new EntityWrapper<>();
        queryWrapper.eq("zichanbianhao", request.getZichanbianhao())
                .eq("yonghuming", request.getYonghuming());
        ZichanjiechuEntity jiechuEntity = zichanjiechuService.selectOne(queryWrapper);
        return jiechuEntity;
    }

    /**
     *
     */
    @PostMapping("getzcjc")
    public R getzcpie(@RequestBody ChartsRequestData chartsRequestData) {
        List<String> x = new ArrayList<>();
        List<Long> y = new ArrayList<>();

        Wrapper<ZichanjiechuEntity> queryWrapper = new EntityWrapper<>();
        if (StringUtils.isNotEmpty(chartsRequestData.getZichanbianhao())) {

            queryWrapper.eq("zichanbianhao", chartsRequestData.getZichanbianhao());
        }

        if (StringUtils.isNotEmpty(chartsRequestData.getShebeimingcheng())) {
            queryWrapper.eq("shebeimingcheng", chartsRequestData.getShebeimingcheng());
        }

        List<ZichanjiechuEntity> zichanjiechuEntities = zichanjiechuService.selectList(queryWrapper);


        Map<String, Long> groupedByNameCount = zichanjiechuEntities.stream()
                .collect(Collectors.groupingBy(ZichanjiechuEntity::getShebeimingcheng, Collectors.counting()));

        groupedByNameCount.forEach((k, v) -> {
            x.add(k);
            y.add(v);
        });

        return R.ok().put("x", x).put("y", y);

    }


    /**
     * 提醒接口
     */
    @RequestMapping("/remind/{columnName}/{type}")
    public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                         @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        map.put("column", columnName);
        map.put("type", type);

        if (type.equals("2")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            Date remindStartDate = null;
            Date remindEndDate = null;
            if (map.get("remindstart") != null) {
                Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindStart);
                remindStartDate = c.getTime();
                map.put("remindstart", sdf.format(remindStartDate));
            }
            if (map.get("remindend") != null) {
                Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindEnd);
                remindEndDate = c.getTime();
                map.put("remindend", sdf.format(remindEndDate));
            }
        }

        Wrapper<ZichanjiechuEntity> wrapper = new EntityWrapper<ZichanjiechuEntity>();
        if (map.get("remindstart") != null) {
            wrapper.ge(columnName, map.get("remindstart"));
        }
        if (map.get("remindend") != null) {
            wrapper.le(columnName, map.get("remindend"));
        }

        String tableName = tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getTablename();
        if (tableName.equals("yonghu")) {
            wrapper.eq("yonghuming", tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getUsername());
        }

        int count = zichanjiechuService.selectCount(wrapper);
        return R.ok().put("count", count);
    }


}
